import pymysql
from pymysql.converters import escape_string
#创建一个类，包含各种数据库函数的调用
class Result:
    #初始化函数，包含数据库url，密码，数据库名
    def __init__(self,**data):
        self.url = data['url']
        self.user = data['user']
        self.password =  data['password']
        self.db = data['db']
        

    def start(self):
        self.conn = pymysql.connect(host=self.url,user=self.user,password=self.password,db=self.db)
        self.cursor = self.conn.cursor()



    #查询函数，返回一个字典
    def query(self,table_name):
        self.cursor.execute("select * from {name}".format(name=table_name))
        # #获取查询结果
        result = self.cursor.fetchall()
        # #关闭游标
        return result   
    
    def query_by_id(self,username):
        self.cursor.execute("select * from user where nickname='{name}'".format(name=username))
        # #获取查询结果
        result = self.cursor.fetchone()
        # #关闭游标
        return result
    
    def query_by_user_id(self,id):
        self.cursor.execute("select * from user where user_id='{name}'".format(name=id))
        # #获取查询结果
        result = self.cursor.fetchone()
        # #关闭游标
        return result

    
    def insert(self,**data):
        self.cursor.execute("insert into user(user_desc,password,nickname,head) values(%s,%s,%s,%s)",(data['user_desc'],data['password'],data['nickname'],data['head']))
        self.conn.commit()

    def delete(self,table_name,id):
        self.cursor.execute("delete from {name} where user_id={id}".format(name=table_name,id=id))
        self.conn.commit()

    def update(self,id,**data):
        self.cursor.execute("update user set user_desc='{user_desc}',password='{password}',nickname='{nickname}' where user_id={id}".format(user_desc=data['user_desc'],password=data['password'],nickname=data['nickname'],id=id))
        self.conn.commit()
    
    def update_head(self,head,id):
        self.cursor.execute("update user set head=%s where user_id=%s",(head,id))
        self.conn.commit()

    def close(self):
        self.cursor.close()
        self.conn.close()

    def settings(self,**data):
        self.url = data['url']
        self.user = data['user']
        self.password = data['password']
        self.db = data['db']


 